package uit.mmt02.noibo;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import uit.mmt02.share.OneMail;

import android.util.Log;

public class MailNoiBoControl 
{
	//bien
//	List<OneMail>list; //list chua cac mail
	private String server; // ip server
	private int port; //port nhan mail
//	private int smtp_port; //port gui mail
	private String username; 
	private String password;
	
//	private String email_adr; //User emaiil address
//    private ArrayList<String> messageBody;
//    private ArrayList<String> sender;
//    private ArrayList<String> subject;
//    private ArrayList<String> date;
    private int ttmsg = 0; //Biáº¿n lÆ°u giÃ¡ trá»‹ tá»•ng sá»‘ mail trong há»™p mail   
	Socket getPipe; //Táº¡o socket
    InputStream instr;
    OutputStream oustr;
    BufferedReader in;
    PrintWriter out;
	public MailNoiBoControl(String server,String username, String password, int port)
	{
		this.server = server;
		this.username = username;
		this.password = password;
		this.port = port;
//		this.smtp_port = smtp_port;
	}
	
	public List<OneMail> getMailNoiBo()
	{
		
		List<OneMail>list  = new ArrayList<OneMail>();
		try
		{
			
			getPipe = new Socket(server,port);
	        instr = getPipe.getInputStream();
	        oustr = getPipe.getOutputStream();
	        in = new BufferedReader(new InputStreamReader(instr)); //Táº¡o buffer reader Ä‘á»�c dá»¯ liá»‡u tá»« server
	        out = new PrintWriter(new OutputStreamWriter(oustr),true);//Táº¡o buffer writer gá»­i dá»¯ liá»‡u cho server!
//	        messageBody = new ArrayList<String>();
//	        date = new ArrayList<String>();
//	        sender = new ArrayList<String>();
//	        subject = new ArrayList<String>();        
	        if (instr==null || oustr == null)
	            return null;
	        String srvmsg; //Biáº¿n chuá»—i LÆ°u thÃ´ng tin server gá»­i tá»›i
	        srvmsg = in.readLine();
	        Log.v("Noi BO 1 ", srvmsg, null);
	        out.println("USER "+username); //Gá»­i user name cá»§a ngÆ°á»�i dÃ¹ng
	        srvmsg = in.readLine();
	        Log.v("Noi BO 2", srvmsg, null);
	        out.println("PASS "+password); //Gá»­i password
	        srvmsg = in.readLine();
	        if(srvmsg.startsWith("-ERR"))
	        {
//	            JOptionPane.showMessageDialog(mainPanel, "Ä�Äƒng nhÃ¢p tháº¥t báº¡i, báº¡n hÃ£y kiá»ƒm tra láº¡i cÃ¡c thiáº¿t láº­p",
//	                    "Login Fail", JOptionPane.ERROR_MESSAGE);
//	            wk_dlg.dispose();
	        	Log.v("Loi Noi bo ", "Loi ERR : " + srvmsg, null);
	            return null;
	        }
	        Log.v("Noi BO 3", srvmsg, null);
	        out.println("STAT");//Láº¥y tráº¡ng thÃ¡i há»™p mail
	        srvmsg = in.readLine();
	        String[] rs = srvmsg.split("\\s");//Láº¥y tá»•ng sá»‘ mail trong há»™p mail tá»« dá»¯ liá»‡u mÃ  server chuyá»ƒn vá»�
	        ttmsg = Integer.parseInt(rs[1]);   
	        for (int i = 1;i<=ttmsg;i++)
	        {
	            String tmp = "";
	            out.println("RETR "+i); //Gá»­i lá»‡nh láº¥y thÆ°
	            srvmsg = in.readLine();
	            srvmsg = in.readLine();
	            OneMail om = new OneMail();
	            while (!srvmsg.equalsIgnoreCase(".")) //Náº¿u chuá»—i server gá»­i vá»� khÃ¡c .
	            {
	            	
	                if(srvmsg.indexOf("From:")!= -1)//Láº¥y thÃ´ng tin sender
//	                        sender.add(srvmsg.substring(srvmsg.indexOf("From:")+5,srvmsg.length()).trim());
	                		om.setFrom(srvmsg.substring(srvmsg.indexOf("From:")+5,srvmsg.length()).trim());
	                if(srvmsg.indexOf("Subject:")!= -1)//Láº¥y Subject
//	                       subject.add(srvmsg.substring(srvmsg.indexOf("Subject:")+8,srvmsg.length()).trim());
	                		om.setSub(srvmsg.substring(srvmsg.indexOf("Subject:")+8,srvmsg.length()).trim());
	                if(srvmsg.indexOf("Date:")!= -1)//Láº¥y Date
//	                       date.add(srvmsg.substring(srvmsg.indexOf("Date:")+5,srvmsg.length()).trim());
	                	om.setDateSend(srvmsg.substring(srvmsg.indexOf("Date:")+5,srvmsg.length()).trim());
	                if (srvmsg.length() == 0)//Báº¯t Ä‘áº§u 1 hÃ ng trá»‘ng -> Mail Body
	                {
	                    srvmsg = in.readLine();
	                    while (!srvmsg.equalsIgnoreCase("."))
	                    {
	                        tmp += srvmsg +"\r\n";
	                        srvmsg = in.readLine();
	                    }
//	                    messageBody.add(i-1,tmp); //ThÃªm ná»™i dung thÆ° vÃ o biáº¿n messageBody
	                    om.setBody(tmp);
	                    
	                }
	                if(!srvmsg.equalsIgnoreCase("."))
	                srvmsg = in.readLine();
	                
	            }
	            //Náº¿u 1 trong cÃ¡c trÆ°á»�ng sender, subject, date khÃ´ng cÃ³ -> thÃªm vÃ o "None"
//	            if(sender.size()< i)
//	                sender.add("None");
//	            if(subject.size()<i)
//	                subject.add("None");
//	            if(date.size()<i)
//	                date.add("None");
	            
	            Log.v("Noi bo", "add " + i);
	            list.add(om);
	        }        
	        out.println("QUIT");//Logout
	        srvmsg =in.readLine();
	        in.close();
	        out.close();
	        getPipe.close();//Ä�Ã³ng socket
	        Log.v("Noi bo", "Co "+rs[1]+" la mail");
		}
		catch (Exception e) 
		{
			// TODO: handle exception
			Log.v("BOI BO", "Loi getmail noi bo: " + e.toString(), null);
		}
		return list;
	}
	

}
